package utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtils {
	/*
	 * 读取Hibernate.cfg.xml文件
	 */
	private static SessionFactory factory;
	private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	static {
		try {
			StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();

			Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
					.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
			factory = metadata.getSessionFactoryBuilder().build();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public HibernateUtils() {
		// TODO Auto-generated constructor stub
	}

	/*
	 * 打开Session
	 */

	public static Session getSession() {

		Session session = (Session) threadLocal.get();
		if (session == null) {
			session = factory.getCurrentSession();
			threadLocal.set(session);
		}
		return session;
	}
	/*
	 * 关闭Session
	 */

	public static void closeSession() {
		Session s = (Session) threadLocal.get();
		if (s != null) {
			s.close();
			threadLocal.set(null);
		}
	}

	public static SessionFactory getSessionFactory() {
		return factory;
	}
}